#import "ChatScrollView.h"
#import "ChatTextView.h"

#import <CoreServices/CoreServices.h>

@implementation ChatScrollView
- (id)initWithFrame:(NSRect)r {
	if(self = [super initWithFrame:r]) {
		name = nil;
		alpha = 0.0;
		NSLog(@"HEYHEYHEYHEYHEYHEYHEY");
	}
	return self;
}

- (void)dealloc {
	[name release];
	name = nil;
	[super dealloc];
}

- (void)setName:(NSString *)n {
	[n retain];
	[name release];
	name = n;
}

- (void)animateNameWithMaxAlpha:(float)max {
	alphatarget = max>alphatarget?max:alphatarget;
	start = [[NSDate alloc] init];
	float alpha = alphatarget;
	[self performSelector:@selector(runAnimation) withObject:nil afterDelay:0.0];
}

const float duration = 0.87;
const float piovertwo = 3.14156/2.0;
- (void)runAnimation {
	float delta = -[start timeIntervalSinceNow];
	if(delta < duration) {
		float percent = delta/duration;
		float x;
		percent*=percent;
		if(percent < 0.5) {
			x = piovertwo * percent;
			alpha = alphatarget - ((alphatarget-0.1)/2)*tan (x);
		}
		else {
			x = piovertwo * (1 - percent);
			alpha = 0.1 + ((alphatarget-0.1)/2)*tan (x);
		}
		if([self lockFocusIfCanDraw]) {
			[self drawName];
			[self unlockFocus];
		}
		[self performSelector:@selector(runAnimation) withObject:nil afterDelay:(1.0/40.0)];
	}
	else {
		alphatarget = 0;
		[start release];
		start = nil;
		[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(runAnimation) object:nil];
		[[self documentView] setNeedsDisplay:YES];
	}
}
	

- (void)drawName {
	float drawalpha = alpha;
	if(drawalpha < 0.1)
		drawalpha = 0.1;
		NSString *title=name;
		
		NSFont *f = [NSFont systemFontOfSize:18];
		NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
		[mps setAlignment:NSRightTextAlignment];
		NSColor *c = [NSColor controlTextColor];
		c = [c colorWithAlphaComponent:drawalpha];

		
		NSAttributedString *as = [[NSAttributedString alloc] initWithString:title
			attributes:[NSDictionary dictionaryWithObjectsAndKeys:
				f,NSFontAttributeName,
				mps,NSParagraphStyleAttributeName,
				c,NSForegroundColorAttributeName,
				nil]
			];
		[mps release];
				
		NSTextFieldCell *tfc = [[NSTextFieldCell alloc] initTextCell:@""];
		[tfc setAttributedStringValue:as];
		[as release];
		ChatTextView *ctv = (ChatTextView *)[self documentView];
//		NSRect r = [self frame];
		NSRect r = [ctv frame];
		NSRect r3 = NSInsetRect(r,5,15);
//		r.size.height = 40;
//		r.size.height = 40;		
		NSRect r2 = [self convertRect:r toView:ctv];
		if([ctv lockFocusIfCanDraw]) {
			[ctv drawNameWithRect:r2];
			[ctv unlockFocus];
		}
		[tfc drawWithFrame:r3 inView:self];
		[tfc release];
		[[self window] flushWindow];
}
@end
